package action.article;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.ArticleManager;
import service.impl.ArticleManagerImpl;

public class ListArticleAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		int articleCount;
		int pageCount;

		ArticleManager am = new ArticleManagerImpl();
		int articleType_Id;
		String articleTypeIdStr = request.getParameter("articleTypeId");
		System.out.println("-------------" + articleTypeIdStr);
		if (articleTypeIdStr == null || articleTypeIdStr.trim().equals("")) {
			articleType_Id = 0;
		}
		try {
			articleType_Id = Integer.parseInt(articleTypeIdStr.trim());
		} catch (Exception e) {
			articleType_Id = 0;
		}
		if (articleType_Id == 0) {
			articleCount = am.getArticleCount();
			pageCount = am.getPageCount(articleCount, am.ARTICLE_PAGE_SIZE);
		} else {
			articleCount = am.getArticleCountByType(articleType_Id);
			pageCount = am.getPageCountByType(articleCount, am.ARTICLE_PAGE_SIZE);
		}
		int pageNo;
		String pageNoStr = request.getParameter("pageNo");
		if (pageNoStr == null || pageNoStr.trim().equals("")) {
			pageNo = 1;
		}
		try {
			pageNo = Integer.parseInt(pageNoStr.trim());
		} catch (Exception e) {
			pageNo = 1;
		}
		if (pageNo > pageCount) {
			pageNo = pageCount;
		}
		request.setAttribute("no", (pageNo - 1) * am.ARTICLE_PAGE_SIZE);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("currentPage", pageNo);
		if (articleType_Id == 0) {
			request.setAttribute("articleList", am.getAllArticleByPage(pageNo));
		} else {
			request.setAttribute("articleList", am.getAllArticleByTypeByPage(articleType_Id, pageNo));		
		}
		request.setAttribute("articleTypeId", ""+articleType_Id);
		request.setAttribute("articleTypeList", am.getAllArticleType());
		request.setAttribute("msg", am.getMsg());
		request.getSession().setAttribute("PRE_URL", request.getHeader("Referer"));
		return mapping.findForward("listArticle");
	}

}
